package com.itheima.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

@Component
public class RabbitConfig {
    @Autowired
    RabbitAdmin rabbitAdmin;
    @Autowired
    Queue GoodsQueue;
    @Autowired
    Exchange GoodsExchange;
    @Bean("GoodsQueue")
    public Queue GoodsQueue() {
        return QueueBuilder.durable("GoodsQueue").build();

    }

    @Bean("GoodsExchange")
    public Exchange GoodsExchange() {
        return ExchangeBuilder.directExchange("GoodsExchange").build();
    }

    @Bean
    public Binding GoodsBinding(@Qualifier("GoodsQueue") Queue deadQueue, @Qualifier("GoodsExchange") Exchange deadExchange) {
        return BindingBuilder.bind(deadQueue).to(deadExchange).with("GoodsRoutingKey").noargs();
    }
    @Bean
    public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
        RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
        // 只有设置为 true，spring 才会加载 RabbitAdmin 这个类
        rabbitAdmin.setAutoStartup(true);
        return rabbitAdmin;
    }
    //创建交换机和对列
    @Bean
    public void createExchangeQueue (){

        rabbitAdmin.declareExchange(GoodsExchange);
        rabbitAdmin.declareQueue(GoodsQueue);

    }

}
